/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.service.impl;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.log4j.Logger;
import org.app.dto.google.Pages;
import org.app.dto.google.ResponseDataJson;
import org.app.dto.google.Results;
import org.app.service.GoogleService;
import org.app.utils.PropertiesHelper;
import org.app.utils.PropertyUtils;
import org.gui.AutoDownloadMovieGUI;

/**
 *
 * @author LamLe
 */
public class GoogleAPI_ServiceImpl extends GoogleAbstract implements GoogleService {
    
    private static Logger logger = Logger.getLogger(GoogleAPI_ServiceImpl.class);
    
    public GoogleAPI_ServiceImpl(AutoDownloadMovieGUI main) {
        super(main);
    }
    
    @Override
    public ResponseDataJson search(String movieName) throws Exception {
        ResponseDataJson results = new ResponseDataJson();
        try {
            movieName = generateUrl(movieName);
            URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&hl=vi&rsz=8&q=" + movieName);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // init heaeder
            initRequestHeader(conn, "ajax.googleapis.com");
            
            InputStream content = new GZIPInputStream(conn.getInputStream());
            BufferedReader rd = new BufferedReader(new InputStreamReader(content));
            
            
            Gson gson = new Gson();
            String json = rd.readLine();
            rd.close();
            results = gson.fromJson(json, ResponseDataJson.class);

            // test
            List<Results> urls = results.getResponseData().getResults();
            int n = 1;
            for (Results r : urls) {
                log("URL " + n++ + " :  " + r.getUrl());
            }
            
        } catch (Exception e) {
            logger.error("Failed", e);
            throw e;
        }
        return results;
    }
    
    @Override
    public ResponseDataJson search(String movieName, int page, ResponseDataJson json1) throws Exception {
        try {
            movieName = generateUrl(movieName);
            // start
            String start = "&start=";
            for (Pages p : (List<Pages>) json1.getResponseData().getCursor().getPages()) {
                if (Integer.parseInt(p.getLabel().toString()) == page) {
                    start += p.getStart();
                }
            }
            URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&hl=vi&rsz=8&q=" + movieName + start);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // init heaeder
            initRequestHeader(conn, "ajax.googleapis.com");
            
            InputStream content = new GZIPInputStream(conn.getInputStream());
            BufferedReader rd = new BufferedReader(new InputStreamReader(content));
            
            
            Gson gson = new Gson();
            String json = rd.readLine();
            rd.close();
            ResponseDataJson result = gson.fromJson(json, ResponseDataJson.class);

            // add results to current json1
            json1.getResponseData().getResults().addAll(result.getResponseData().getResults());

            // test
            List<Results> urls = json1.getResponseData().getResults();
            int n = 1;
            for (Results r : urls) {
                log("URL " + n++ + " :  " + r.getUrl());
            }
        } catch (Exception e) {
            logger.error("Failed", e);
            throw e;
        }
        return json1;
    }
    
    @Override
    public ResponseDataJson search24(String movieName) throws Exception {
        ResponseDataJson results = new ResponseDataJson();
        try {
            movieName = generateUrl(movieName);
            Gson gson = new Gson();
            String json = "";
            String start = "&start=";
            String quatity = "&rsz=";
            Double config = Double.parseDouble(PropertyUtils.getProperty(PropertiesHelper.GOOGLE_SEARCH_RESULTS));
            Double number = Math.ceil(config / 8);
            int n = number.intValue();
            for (int i = 0; i < n; i++) {
                
                start = "&start=";
                quatity = "&rsz=";
                start += i == 0 ? "0" : i * 8;
                quatity += (config - (i * 8)) < 8 ? config - (i * 8) : 8;
                
                URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&hl=vi&rsz=8&q=" + movieName + start + quatity);
                logger.info("Google : " + url.toString());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // init heaeder
                initRequestHeader(conn, "ajax.googleapis.com");
                InputStream content = new GZIPInputStream(conn.getInputStream());
                BufferedReader rd = new BufferedReader(new InputStreamReader(content));
                json = rd.readLine();
                rd.close();
                
                if (i == 0) {
                    results = gson.fromJson(json, ResponseDataJson.class);
                } else {
                    ResponseDataJson tmp = gson.fromJson(json, ResponseDataJson.class);
                    results.getResponseData().getResults().addAll(tmp.getResponseData().getResults());
                    results.getResponseData().getCursor().setResultCount(tmp.getResponseData().getCursor().getResultCount());
                }
                String numberOfResults = results.getResponseData().getCursor().getResultCount();
                numberOfResults = numberOfResults.replace(".", "");
                if (Integer.parseInt(numberOfResults) <= ((i + 1) * 8)) {
                    logger.info("Google break - number of results : " + numberOfResults);
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("Failed", e);
            throw e;
        }
        return results;
    }
}
